home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 3719 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.8 KB

  1. Path: news.chattanooga.net!usenet
  2. From: "Eric W. Bradway" <ebradway@microsports.com>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Help using qsort to sort pointers to a structure
  5. Date: Tue, 30 Jan 1996 12:52:54 -0500
  6. Organization: Micro Sports, Inc.
  7. Message-ID: <310E5AF6.5B55@microsports.com>
  8. References: <4eg8rp$2oo_001@news2.cts.com>
  9. NNTP-Posting-Host: 205.244.28.38
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0b5 (Win95; I)
  14.  
  15. William Rinehart wrote:
  16. > qsort((void *)data, (size_t)4, sizeof(struct alpha *), compname);
  17.  
  18. sizeof(struct alpha *) gives the size of a pointer to struct alpha 
  19. (i.e., 4 on most machines) so when qsort starts copying stuff around it 
  20. only copies the first four byte!
  21.  
  22. > int
  23. > compname(const void *arg1, const void *arg2)
  24. > {
  25. >         /* cast arg1 and arg2 as pointers to pointers, then derefence
  26. >                 so that strcmp gets "regular" pointer as arguments */
  27. >         return (strcmp((*(struct alpha**)arg1)->names, (*(struct alpha**)arg2)->names));
  28. > }
  29.  
  30. Here you want to cast to (struct alpha *) only so it knows what type 
  31. arg1 and arg2 really are. Casting to (struct alpha **) make the compiler 
  32. think that what arg1 is pointing to is a pointer and when you 
  33. dereference this non-pointer it is pointing to someplace in 
  34. never-never-land (actually in this case, for the first string it would 
  35. be whatever your system translated the four bytes "aaa\0" to).
  36.  
  37. I'm not much of an expert on this (I had to look at some of my code that 
  38. works to tell you exactly what is wrong) but I would suggest getting a 
  39. good ANSI C book that provides examples for functions like qsort. I use 
  40. qsort so infrequently myself that I always start by reviewing working 
  41. code (and usually just copying and modifying it).
  42.  
  43. Good luck...
  44. -Eric
  45.